package com.zoffy.oj_backend.judge;

import cn.hutool.json.JSONUtil;
import com.zoffy.oj_backend.common.ErrorCode;
import com.zoffy.oj_backend.exception.BusinessException;
import com.zoffy.oj_backend.judge.codesandbox.CodeSandbox;
import com.zoffy.oj_backend.judge.codesandbox.CodeSandboxFactory;

import com.zoffy.oj_backend.judge.codesandbox.model.ExecuteCodeRequest;
import com.zoffy.oj_backend.judge.codesandbox.model.ExecuteCodeResponse;
import com.zoffy.oj_backend.judge.codesandbox.model.JudgeInfo;
import com.zoffy.oj_backend.judge.strategy.JudgeContext;
import com.zoffy.oj_backend.model.dto.question.JudgeCase;
import com.zoffy.oj_backend.model.entity.Question;
import com.zoffy.oj_backend.model.entity.QuestionSubmit;
import com.zoffy.oj_backend.model.enums.JudgeInfoMessageEnum;
import com.zoffy.oj_backend.model.enums.QuestionSubmitStatusEnum;
import com.zoffy.oj_backend.model.vo.QuestionResultVo;
import com.zoffy.oj_backend.model.vo.QuestionSubmitTinyVo;
import com.zoffy.oj_backend.service.QuestionService;
import com.zoffy.oj_backend.service.QuestionSubmitService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;


@Service

public class JudgeImpl implements JudgeService {
    @Resource
    private QuestionService questionService;
    @Resource
    private QuestionSubmitService questionSubmitService;
    @Resource
    private JudgeManager judgeManager;
    @Value("${codesandbox.type:example}")
    private String type;

    @Override
    @Transactional
    public QuestionResultVo doJudge(long questionSubmitId) {
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交记录不存在");
        }
        //获取输入用例
        Question question = questionService.getById(questionSubmit.getQuestionId());
        List<JudgeCase> judgeCaseList = questionService.getJudgeCases(question.getJudgeCase());
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).toList();
        //通过静态工厂获得代码沙箱
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        //代码沙箱执行代码获取结果
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(questionSubmit.getCode())
                .language(questionSubmit.getLang())
                .inputList(inputList).build();
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
        String lock= ("questionSubmit_" + question.getId()).intern();
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        JudgeInfo judgeInfo=new JudgeInfo();
        if(executeCodeResponse.getStatus().equals(QuestionSubmitStatusEnum.EXIT_NORMAL.getValue())){
            JudgeContext judgeContext = new JudgeContext();
            judgeContext.setLang(questionSubmit.getLang());
            judgeContext.setOutputList(executeCodeResponse.getOutputList());
            judgeContext.setJudgeCaseList(judgeCaseList);
            judgeContext.setQuestion(question);
            judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
            judgeInfo= judgeManager.doJudge(judgeContext);
            //更新题目提交状态

            questionSubmitUpdate.setId(questionSubmitId);

            questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
            questionSubmitUpdate.setState(QuestionSubmitStatusEnum.EXIT_NORMAL.getValue());
            questionSubmitService.updateById(questionSubmitUpdate);
            synchronized (lock){
                question=questionService.getById(question.getId());
                question.setSubmitNum(question.getSubmitNum()+1);
                if(judgeInfo.getMessage().equals(JudgeInfoMessageEnum.ACCEPTED.getText())){
                    question.setAcceptedNum(question.getAcceptedNum()+1);
                }
                questionService.updateById(question);
            }

        }else {
            //更新题目提交状态
            questionSubmitUpdate.setId(questionSubmitId);
            judgeInfo.setMessage(executeCodeResponse.getMessage());
            questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
            questionSubmitUpdate.setExtra(executeCodeResponse.getExtra());
            questionSubmitUpdate.setState(executeCodeResponse.getStatus());
            questionSubmitService.updateById(questionSubmitUpdate);
            synchronized (lock){
                question=questionService.getById(question.getId());
                question.setSubmitNum(question.getSubmitNum()+1);
                questionService.updateById(question);
            }
        }
        QuestionResultVo resultVo=new QuestionResultVo();
        resultVo.setExtra(questionSubmitUpdate.getExtra());
        resultVo.setJudgeInfo(judgeInfo);
        return resultVo;
    }
}
